class Company < ActiveRecord::Base
  acts_as_tree :order=>'position'
  acts_as_list :scope=>'parent_id'
  has_many :users,:conditions=>["destroyed = 0 or destroyed is null"], :order => 'id'
  has_many :removed_users, :class_name =>'User', :conditions=>["destroyed = 1"],:order => 'id desc'
  has_many :projects,:order=>'id DESC'
  has_many :activity_types
  has_many :active_projects, :class_name=>'Project',:conditions=>["projects.completed = 'No' or projects.completed is NULL"],:order=>'id desc'
  has_many :completed_projects, :class_name=>'Project',:conditions=>["completed='Yes'"]
  has_many :payments,:order=>'id desc'
  has_many :roles

  #default categories
  has_many :msg_categories,  :class_name =>'Category', :conditions=>"label = 'msg'", :order => 'id DESC',:dependent=>:destroy
  has_many :wb_categories,  :class_name =>'Category', :conditions=>"label = 'wb'", :order => 'id DESC',:dependent=>:destroy
  has_many :file_categories,  :class_name =>'Category', :conditions=>"label = 'fs'", :order => 'id DESC',:dependent=>:destroy

  belongs_to :plan
  validates_uniqueness_of :url
  validates_presence_of   :name    

#license end at
def license_end_at
  if self.plan.name == "Free"
    "Free".t
  else
    if self.payments.size > 0
      ((self.payments.last.amount*30).to_f/self.plan.price_cn).to_i.day.since(self.payments.last.created_at).strftime("%Y-%m-%d")
    else
      1.month.since(self.created_at).strftime("%Y-%m-%d")
    end
  end
end
def balance
    if self.payments.size > 0
      ((self.payments.last.amount).to_f/self.plan.price_cn) * (self.payments.last.created_at).strftime("%Y-%m-%d")
    else
      "No Balance".t
    end
end
#message size
def message_size
   ts = Message.find_by_sql("SELECT count(id) as sum FROM messages where project_id in (#{self.projects.collect{|p| p.id}.join(",")})") 
   ts.first.sum.to_i
end
#todo size
def todo_size
   ts = Todo.find_by_sql("SELECT count(id) as sum FROM todos where project_id in (#{self.projects.collect{|p| p.id}.join(",")})") 
   ts.first.sum.to_i
end  

def todos
   Todo.find_by_sql("SELECT * FROM todos where project_id in (#{self.projects.collect{|p| p.id}.join(",")}) order by project_id desc,id desc") 
end  


#writeboard size
def writeboard_size
   ts = Writeboard.find_by_sql("SELECT count(id) as sum FROM writeboards where project_id in (#{self.projects.collect{|p| p.id}.join(",")})") 
   ts.first.sum.to_i
end

def project_users(p_id)
   User.find_by_sql("select users.* from users,tasks where tasks.project_id = #{p_id} and tasks.user_id = users.id and (destroyed = 0 or destroyed is null) order by tasks.id")
end

def account_owner
  if self.owner_id
   User.find(self.owner_id)
  else
   User.find(:first,:conditions=>"id = (select min(id) from users where company_id = #{self.id})")
  end
end 

def send_notify_email
  Notifier.deliver_signup_thanks(self.administrator)
end
end
